package com.anxinr.init;

import cn.hutool.core.util.ObjectUtil;
import com.anxinr.constant.RedisConstant;
import com.anxinr.controller.PanicBuyingController;
import com.anxinr.pojo.dto.ShoppingDto;
import com.anxinr.pojo.entity.Goods;
import com.anxinr.pojo.entity.ShoppingInfo;
import com.anxinr.service.GoodsService;
import com.anxinr.service.ShoppingInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.beans.beancontext.BeanContext;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author : anxinr
 * @date : 2023/9/22 18:22
 */
@Component
public class PanicBuyingInit {
    @Autowired
    private GoodsService goodsService ;

    @Autowired
    private StringRedisTemplate redisTemplate ;

    @Autowired
    private ShoppingInfoService infoService ;

    @Autowired
    private Executor asyncExecutor ;

    public PanicBuyingInit(){
        new Thread(()->{
            while (ObjectUtil.isNull(goodsService) || ObjectUtil.isNull(redisTemplate)){

            }
            List<Goods> list = goodsService.list();
            for (Goods goods : list) {
                redisTemplate.opsForValue().set(
                        RedisConstant.GOODS_CACHE_INVENTORY +
                                goods.getId() ,
                        goods.getInventory() + "" ,
                        RedisConstant.GOODS_CACHE_INVENTORY_TIME ,
                        TimeUnit.MINUTES
                );
            }

            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ThreadPoolTaskExecutor ses = (ThreadPoolTaskExecutor) asyncExecutor ;

            for (int i = 1; i <= 2000; i++) {
                for (int j = 0; j < 10; j++) {
                    int finalI = i;
                    for (Goods goods : list) {
                        asyncExecutor.execute(()->{
                            ShoppingDto dto = new ShoppingDto();
                            dto.setUserId(finalI + 0L);
                            dto.setGoodsId(goods.getId());
                            ShoppingInfo buying = infoService.buying(dto);
                            System.out.println("buying = " + buying);
                        });
                    }
                }
            }
        }).start();
    }

}
